var dbmodel = require('../dbmodel/dbmodel.js');
var postComment = dbmodel.model('postComments');

// 更改文章的评论数量
let postInfoChange = function(postID, value, success, fail, res) {
	let wherestr = {
		'_id': postID
	}
	let query = post.find(wherestr);

	// 查询结果
	query.exec().then(function(e) {
		post.updateOne(wherestr, {
			comment: value
		}, function(err, result) {
			if (err) {
				res.send({
					status: 500,
					info: fail
				});
			} else {
				res.send({
					status: 200,
					info: success
				})
			}
		})
	}).catch(function(err) {
		res.send({
			status: 500,
			err
		})
	})
}
// 获取评论列表
exports.commentListGet = function(req, res) {
	let wherestr = {
		'postID': req.body.postID
	}
	let query = postComment.find(wherestr);
	// 查找postID的关联集合 user
	query.populate('userID');
	query.populate('postID');
	// 排序方式 time 倒序（-1倒叙，1正序）
	query.sort({
		'createTime': req.body.arrangement
	});
	// 查询结果
	query.exec().then(function(e) {
		res.send({
			status: 200,
			info: e
		});
	}).catch(function(err) {
		res.send({
			status: 500,
			err
		})
	})
}

// 评论发布
exports.postCommentUpload = function(req, res) {
	let data = {
		userID: req.body.userID,
		postID: req.body.postID,
		text: req.body.text,
		like: 0,
		comment: 0,
		createTime: new Date()
	}

	let PostComment = new postComment(data)
	PostComment.save(function(err, result) {
		if (err) {
			res.send({
				status: 500,
				info: '评论上传失败'
			})
		} else {
			postInfoChange(req.body.postID,req.body.value,'评论上传成功','评论上传失败')
		}
	})
}
